package com.taoym.voucher.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: taoym
 * @date: 2021/3/24 21:53
 * @desc: todo
 */
public class ThreadPoolFactory implements ThreadFactory {
    // 线程池号
    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    // 线程号
    private static final AtomicInteger threadNumber = new AtomicInteger(1);
    // 线程池前缀名称
    private final String namePrefix;

    public ThreadPoolFactory(String namePrefix) {
        this.namePrefix = "ThreadPoolFactory--" + namePrefix + "--Work";
    }

    @Override
    public Thread newThread(Runnable r) {
        int threadId = threadNumber.getAndIncrement();
        String threadName = namePrefix + "--" + threadId;
        return new Thread(null, r, threadName, 0);
    }
}

/**
 * @author: taoym
 * @date: 2021/3/24 22:07
 * @desc: 自定义线程池拒绝策略
 */
class ThreadPoolRejectHandler implements RejectedExecutionHandler {

    private static final Logger LOG = LoggerFactory.getLogger(ThreadPoolFactory.class);

    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        LOG.warn("task rejected" + executor.toString());
    }
}
